package com.xywl.escort.view.market;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.trello.rxlifecycle2.LifecycleTransformer;
import com.xywl.escort.R;
import com.xywl.escort.adapter.MarketAdapter;
import com.xywl.escort.adapter.NetworkImageHolderView;
import com.xywl.escort.base.BaseFragment;
import com.xywl.escort.bean.BannerResp;
import com.xywl.escort.bean.GoodListReq;
import com.xywl.escort.bean.MarketDataBean;
import com.xywl.escort.bean.MarketListResp;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;
import dagger.android.support.AndroidSupportInjection;
import qiu.niorgai.StatusBarCompat;
import timber.log.Timber;

public class MarketFragment extends BaseFragment implements MarketContract.View, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private static final String ARG_PARAM1 = "param1";
    @BindView(R.id.recycler_market)
    RecyclerView mRecyclerMarket;
    @BindView(R.id.convenientBanner)
    ConvenientBanner mConvenientBanner;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R.id.progress_bar)
    ProgressBar mProgressBar;
    @BindView(R.id.layout_content)
    CoordinatorLayout mLayoutContent;
    @BindView(R.id.edit_search)
    EditText mEditSearch;
    @BindView(R.id.text_sort_type)
    TextView mTextSortType;

    private PopupWindow mPopWindow;

    private MarketAdapter mAdapter;

    private int mType = 0;

    private int pageNum = 1;
    private boolean isEnd = false;
    private List<MarketDataBean> mList = new ArrayList<>();

    @Inject
    MarketContract.Presenter mPresenter;

    public MarketFragment() {
        // Required empty public constructor
    }

    public static MarketFragment newInstance(String param1) {
        MarketFragment fragment = new MarketFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public int getLayoutResId() {
        return R.layout.fragment_market;
    }

    @Override
    public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        mTvTitle.setText(getString(R.string.tab_market));
        if (null != this.getActivity()) {
            StatusBarCompat.translucentStatusBar(getActivity(), true);
        }
        GridLayoutManager manager = new GridLayoutManager(this.getActivity(), 2);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerMarket.setLayoutManager(manager);

        mAdapter = new MarketAdapter(R.layout.item_market, mList);
        mRecyclerMarket.setAdapter(mAdapter);

        View emptyView = LayoutInflater.from(this.getActivity()).inflate(R.layout.layout_empty_view, null);
        TextView tvEmpty = emptyView.findViewById(R.id.tv_empty);
        tvEmpty.setText("暂无数据");
        mAdapter.setEmptyView(emptyView);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                MarketDataBean bean = mList.get(position);
                if (null != bean) {
                    String spuId = bean.spuId;
                    String skuId = bean.skuId;
                    ARouter.getInstance()
                            .build("/xy/product/detail")
                            .withString("spuId", spuId)
                            .withString("skuId", skuId)
                            .navigation();
                }
            }
        });

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent, R.color.colorPrimary, R.color.aid_prompt_color, R.color.colorBackground);

        mEditSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                switch (actionId) {
                    case EditorInfo.IME_ACTION_SEARCH:
                        search();
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void initData() {
        mPresenter.takeView(this);
        pageNum = 1;
        mPresenter.loadBanner();
        GoodListReq req = new GoodListReq();
        req.pageNum = pageNum;
        req.type = 0;
        mPresenter.loadMarketList(req);

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mSwipeRefreshLayout.setEnabled(false);
                mRecyclerMarket.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mSwipeRefreshLayout.setEnabled(false);
                        if (isEnd) {
                            //数据全部加载完毕
                            mAdapter.loadMoreEnd();
                            mSwipeRefreshLayout.setEnabled(true);
                        } else {
                            //成功获取更多数据
                            GoodListReq req = new GoodListReq();
                            req.pageNum = pageNum;
                            req.type = mType;
                            mPresenter.loadMarketList(req);
                        }
                    }
                }, 200);
            }
        }, mRecyclerMarket);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            Timber.e("onHiddenChanged hidden");
        } else {
            Timber.e("onHiddenChanged");
            mPresenter.loadBanner();
            pageNum = 1;
            GoodListReq req = new GoodListReq();
            req.pageNum = pageNum;
            req.type = mType;
            mPresenter.loadMarketList(req);
        }
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return this.<T>bindToLifecycle();
    }

    @Override
    public void loadBannerSuccess(final BannerResp resp) {
        mProgressBar.setVisibility(View.GONE);
        mLayoutContent.setVisibility(View.VISIBLE);
        if (null != resp.data) {
            List<BannerResp.DataBean> list = resp.data;
            List<String> bannerList = new ArrayList<>();
            for (BannerResp.DataBean bean : list) {
                bannerList.add(bean.imgUrl);
            }
            mConvenientBanner.setPages(new CBViewHolderCreator() {
                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }
            }, bannerList).setPageIndicator(new int[]{
                    R.mipmap.home_banner2,
                    R.mipmap.home_banner1})
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                    .setOnItemClickListener(new OnItemClickListener() {
                        @Override
                        public void onItemClick(int position) {
                            List<BannerResp.DataBean> bannerData = resp.data;
                            BannerResp.DataBean listBean = bannerData.get(position);
                            if (null != listBean) {
                                switch (listBean.linkType) {
                                    case 1:
                                        ARouter.getInstance().build("/xy/web/links")
                                                .withString("url", listBean.linkContent)
                                                .withString("title", getString(R.string.app_name)).navigation();
                                        break;
                                    case 2:
                                        ARouter.getInstance().build("/xy/project/detail")
                                                .withString("projectId", listBean.linkContent)
                                                .withString("title", "项目详情")
                                                .navigation();
                                        break;
                                    case 3:
                                        String content = listBean.linkContent;
                                        if (!TextUtils.isEmpty(content)) {
                                            ARouter.getInstance().build("/xy/product/detail").withString("spuId", content).navigation();
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                    })
                    .setCanLoop(bannerList.size() > 1);
            if (bannerList.size() > 1) {
                mConvenientBanner.startTurning(5000);
            }
        }
    }

    @Override
    public void loadBannerFailure() {
        mProgressBar.setVisibility(View.GONE);
    }

    @Override
    public void updateMarketList(MarketListResp.DataBean dataBean) {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
        mLayoutContent.setVisibility(View.VISIBLE);

        if (null != dataBean) {
            List<MarketDataBean> dataBeans = dataBean.list;
            if (pageNum == 1) {
                mList.clear();
            }
            if (pageNum >= dataBean.pages) {
                isEnd = true;
            } else {
                isEnd = false;
                pageNum += 1;
            }
            if (null != dataBeans) {
                mList.addAll(dataBeans);
            }
            mAdapter.setNewData(mList);
            mAdapter.loadMoreComplete();
            mSwipeRefreshLayout.setEnabled(true);
        }
    }

    private void showPopupWindow(View view) {
        //设置contentView
        View contentView = LayoutInflater.from(MarketFragment.this.getActivity()).inflate(R.layout.view_popup, null);
        mPopWindow = new PopupWindow(contentView, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        mPopWindow.setContentView(contentView);
        //设置各个控件的点击响应
        TextView textDefaultSort = contentView.findViewById(R.id.text_default_sort);
        TextView textPlatformSort = contentView.findViewById(R.id.text_platform_sort);
        TextView textUserSort = contentView.findViewById(R.id.text_user_sort);
        TextView textPresaleSort = contentView.findViewById(R.id.text_presale_sort);

        ImageView imgDefaultSort = contentView.findViewById(R.id.img_default_sort);
        ImageView imgPlatformSort = contentView.findViewById(R.id.img_platform_sort);
        ImageView imgUserSort = contentView.findViewById(R.id.img_user_sort);
        ImageView imgPresaleSort = contentView.findViewById(R.id.img_presale_sort);
        textDefaultSort.setOnClickListener(this);
        textPlatformSort.setOnClickListener(this);
        textUserSort.setOnClickListener(this);
        textPresaleSort.setOnClickListener(this);

        if (null != this.getActivity()) {
            if (null != this.getActivity()) {
                switch (mType) {
                    case 0: {
                        imgDefaultSort.setVisibility(View.VISIBLE);
                        imgPlatformSort.setVisibility(View.GONE);
                        imgUserSort.setVisibility(View.GONE);
                        imgPresaleSort.setVisibility(View.GONE);
                        textDefaultSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.normal_text_color));
                        textPlatformSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textUserSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPresaleSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                    }
                    break;
                    case 1: {
                        imgPlatformSort.setVisibility(View.VISIBLE);
                        imgDefaultSort.setVisibility(View.GONE);
                        imgUserSort.setVisibility(View.GONE);
                        imgPresaleSort.setVisibility(View.GONE);
                        textPlatformSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.normal_text_color));
                        textDefaultSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textUserSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPresaleSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                    }
                    break;
                    case 2: {
                        imgUserSort.setVisibility(View.VISIBLE);
                        imgDefaultSort.setVisibility(View.GONE);
                        imgPlatformSort.setVisibility(View.GONE);
                        imgPresaleSort.setVisibility(View.GONE);
                        textUserSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.normal_text_color));
                        textDefaultSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPlatformSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPresaleSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                    }
                    break;
                    case 3: {
                        imgPresaleSort.setVisibility(View.VISIBLE);
                        imgDefaultSort.setVisibility(View.GONE);
                        imgPlatformSort.setVisibility(View.GONE);
                        imgUserSort.setVisibility(View.GONE);
                        textPresaleSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.normal_text_color));
                        textDefaultSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPlatformSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textUserSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                    }
                    break;
                    default: {
                        imgDefaultSort.setVisibility(View.VISIBLE);
                        imgPlatformSort.setVisibility(View.GONE);
                        imgUserSort.setVisibility(View.GONE);
                        imgPresaleSort.setVisibility(View.GONE);
                        textDefaultSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.normal_text_color));
                        textPlatformSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textUserSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                        textPresaleSort.setTextColor(ContextCompat.getColor(this.getActivity(), R.color.main_body_normal_color));
                    }
                    break;
                }
            }
        }
//        mPopWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);
        mPopWindow.showAsDropDown(view);
    }

    @Override
    public void loadMarketFailure() {
        mSwipeRefreshLayout.setRefreshing(false);
        mProgressBar.setVisibility(View.GONE);
    }

    @Override
    public void onRefresh() {
        mAdapter.setEnableLoadMore(false);
        pageNum = 1;
        GoodListReq req = new GoodListReq();
        req.pageNum = pageNum;
        req.type = mType;
        mPresenter.loadMarketList(req);
        mPresenter.loadBanner();
    }

    @OnClick({R.id.text_sort_type, R.id.text_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.text_sort_type: {
                showPopupWindow(view);
            }
            break;
            case R.id.text_search: {
                search();
            }
            break;
            default:
                break;
        }
    }

    private void search() {
        if (null != mEditSearch && null != mEditSearch.getText()) {
            String keyword = mEditSearch.getText().toString();
            mSwipeRefreshLayout.setRefreshing(true);
            GoodListReq req = new GoodListReq();
            req.pageNum = pageNum;
            req.spuName = keyword;
            req.type = mType;
            mPresenter.loadMarketList(req);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.text_default_sort: {
                if (null != MarketFragment.this.getActivity()) {
                    mPopWindow.dismiss();
                    mType = 0;
                    marketSort(0);
                    mTextSortType.setText("综合排序");
                }
            }
            break;
            case R.id.text_platform_sort: {
                if (null != MarketFragment.this.getActivity()) {
                    mPopWindow.dismiss();
                    mType = 1;
                    marketSort(1);
                    mTextSortType.setText("平台自营");
                }
            }
            break;
            case R.id.text_user_sort: {
                if (null != MarketFragment.this.getActivity()) {
                    mPopWindow.dismiss();
                    mType = 2;
                    marketSort(2);
                    mTextSortType.setText("用户转卖");
                }
            }
            break;
            case R.id.text_presale_sort: {
                if (null != MarketFragment.this.getActivity()) {
                    mPopWindow.dismiss();
                    mType = 3;
                    marketSort(3);
                    mTextSortType.setText("预售");
                }
            }
            break;
            default:
                break;
        }
    }

    private void marketSort(int type) {
        pageNum = 1;
        GoodListReq req = new GoodListReq();
        req.pageNum = pageNum;
        req.type = type;
        mPresenter.loadMarketList(req);
    }
}
